//
//  EventListViewController.swift
//  foodApp1
//
//  Created by JennyShi on 2018/4/9.
//  Copyright © 2018年 Apple Inc. All rights reserved.
//

import UIKit
import os.log
import Alamofire
import Hyphenate
import MobileCoreServices
import MBProgressHUD

class EventListViewController: UIViewController {

    @IBOutlet weak var mySegmentControl: UISegmentedControl!
    //public calendar
    @IBOutlet weak var myFirstView: UIView!
    //personal calendar
    @IBOutlet weak var mySecondView: UIView!
    
    //传进来的参数
    var statusPara = StatusPara(hasFriend:false,friendOwner:"",loginOwner:"",sourceViewControllerType:1,dateTitle:"",date:Date(),calendarTypeNumber:0,matchOrFree:0,languageNow:"")
    var hasFriend = false
    var isGroup = false
    var friendOwner : String?
    var loginOwner : String?
    var dateTitle : String?
    var dateSelect : Date?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 设置传进来的参数
        if statusPara == statusPara {
            hasFriend = (statusPara?.hasFriend)!
            friendOwner = statusPara?.friendOwner
            loginOwner = statusPara?.loginOwner
            dateSelect = statusPara?.date
            dateTitle = statusPara?.dateTitle
        } else {
            dateSelect = Date()
            let dformatter = DateFormatter()
            dformatter.dateFormat = "yyyy-MM-dd"
            dateTitle = dformatter.string(from: dateSelect!)
            loginOwner = EMClient.shared().currentUsername
        }
        
      
        
        //获取login的userID
        if loginOwner == nil || (loginOwner?.isEmpty)! {
            loginOwner = EMClient.shared().currentUsername
        }
        
        if hasFriend {
            mySegmentControl.isHidden = true
        }
        
        myFirstView.isHidden = false
        mySecondView.isHidden = true

        //获取屏幕大小
        let viewBounds:CGRect = self.view.bounds
        let ciewCenter:CGPoint = self.view.center
        
        //没有扣除上面的标题栏高度
        myFirstView.bounds = viewBounds
        myFirstView.center = ciewCenter
        mySecondView.bounds = viewBounds
        mySecondView.center = ciewCenter
        
        /// FIXME: 添加label 限制长度显示用户名
//
//        var nameText = getNickNameWithUsername(username: loginOwner!)
//
//        let label:UILabel = UILabel(frame:CGRect(x: 0, y: 0, width: 80, height: 44))
//        label.textColor = UIColor.pg_color(withHexString: "#4F5358")
//        label.font = UIFont.systemFont(ofSize: 14)
//        label.text = getNickNameWithUsername(username: loginOwner!)
////        label.backgroundColor = UIColor.yellow
//        let dateBarButtonItem = UIBarButtonItem(customView: label)
//        if hasFriend {
//            nameText = getNickNameWithUsername(username: friendOwner!)
//        }
//
//        if nameText.count > 5 {
//            nameText = nameText.subString(start: 0, length: 5)
//            nameText = nameText + "..."
//        }
//
//        label.text = nameText

        //自定义导航栏右侧的按钮，显示username
//        var dateBarButtonItem = UIBarButtonItem(title: getNickNameWithUsername(username: loginOwner!), style: .plain, target: self, action:nil)
//        if hasFriend {
//            dateBarButtonItem = UIBarButtonItem(title: getNickNameWithUsername(username: friendOwner!), style: .plain, target: self,action:nil)
//        }
//        self.navigationItem.rightBarButtonItems?.append(dateBarButtonItem)
        //删除storyBoard上的Item，不设置并删除Item则date按钮显示不出来
        self.navigationItem.rightBarButtonItems?.remove(at: 0)
        
        //自定义导航栏左侧的返回按钮
        let cancelButtonItem = UIBarButtonItem(title: EnStatic.getWord(keyWord: "Back"), style: .plain, target: self, action: #selector(cancelButtonClicked))
        self.navigationItem.leftBarButtonItem = cancelButtonItem

        mySegmentControl.setTitle(EnStatic.getWord(keyWord: "Public"), forSegmentAt: 0)
        mySegmentControl.setTitle(EnStatic.getWord(keyWord: "Personal"), forSegmentAt: 1)
        
   
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    //MARK: 导航栏左上角的返回键
    @objc func cancelButtonClicked() {
        if let owningNavigationController = self.navigationController{
            owningNavigationController.popViewController(animated: true)
        }else {
            fatalError("The ViewController is not inside a navigation controller.")
        }
    }
    
    @IBAction func indexChanged(_ sender: UISegmentedControl) {
        switch mySegmentControl.selectedSegmentIndex
        {
        case 0:
            myFirstView.isHidden = false
            mySecondView.isHidden = true
        case 1:
            myFirstView.isHidden = true
            mySecondView.isHidden = false
        default:
            break;
        }
        
    }
    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        super.prepare(for: segue, sender: sender)
        switch(segue.identifier ?? "") {
        case "eventFirst":
            os_log("eventFirst", log: OSLog.default, type: .debug)
            guard let eventListViewController = segue.destination as? EventsViewController else {
                fatalError("Unexpected destination: \(segue.destination)")
            }

            //日期和loginOwner传到下一屏
            statusPara?.calendarTypeNumber = 0  //public
            eventListViewController.statusPara = statusPara
            eventListViewController.isGroup = self.isGroup
        case "eventSecond":
            os_log("eventSecond", log: OSLog.default, type: .debug)
            guard let eventListViewController = segue.destination as? EventsViewController else {
                fatalError("Unexpected destination: \(segue.destination)")
            }
            
            //日期和loginOwner传到下一屏
            statusPara?.calendarTypeNumber = 1  //personal
            eventListViewController.statusPara = statusPara
            eventListViewController.isGroup = self.isGroup
        default:
            fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))")
        }
        
    }

    func getNickNameWithUsername(username : String) -> String {
        let entity = EMUserProfileManager.sharedInstance.getUserProfileByUsername(username: username)
        if entity?.nickname != nil && (entity?.nickname?.count)! > 0 {
            return (entity?.nickname)!
        }
        return username
    }
    
}

extension String {
    
    var parseJSONString: AnyObject? {
        
        let data = self.data(using: String.Encoding.utf8, allowLossyConversion: false)
        
        if let jsonData = data {
            // Will return an object or nil if JSON decoding fails
            do {
                return try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
            } catch { }
        }
        // Lossless conversion of the string was not possible
        return nil
    }
    
}

